import React, {
    memo,
    useState,
    forwardRef,
    useMemo,
    useRef,
    useEffect,
    useCallback,
} from 'react';
import { setSelectedType, setFormData } from 'src/context/usetypeformstore';

import useVideoId from 'src/context/usevideoid';
import LazyImage from 'src/components/lazyimage';
import GradientBackground from './gradientbackground';
import GradientBackgroundCss from './gradientbackgroundjustcss';

import CustomControlVideoPlayer from 'src/components/customcontrolvideoplayer';
import ButtonToolList from 'src/components/buttonlist';
import DeleteButton from 'src/components/buttonlist/delete.jsx';
import api from 'api/config';

const VideoItem = memo(({ item, handlepop, loadVideo, addfake }) => {
    const { videoId, videoSelectNum, setVideoId, setvideoSelectNum } =
        useVideoId();
    const [playingVideos, setPlayingVideos] = useState(new Set()); // 管理播放状态
    const types = {
        image: '图片生成',
        video: '视频生成',
    };
    const [generatenum, setGeneratenum] = useState(item.onceGenerateNum);

    const horizontalRatios = ['1:1', '16:9', '4:3', '3:2', '2:1'];

    const options = [
        {
            value: 1,
            label: '1',
        },
        {
            value: 2,
            label: '2',
        },
        {
            value: 3,
            label: '3',
        },
        {
            value: 4,
            label: '4',
        },
    ];
    const kuozhan = {
        variation: { 0: '轻微变化', 1: '强烈变化' },
        upscale: { 0: '稳定超分', 1: '创意超分' },
        remix: { 0: '强烈重塑', 1: '轻微重塑' },
    };

    const handleRewrite = useCallback((item) => {
        setSelectedType(item.type);

        if (item.type === 'image') {
            setFormData('image', item.params);
        }
        if (item.type === 'video') {
            if (item.params.isLoop == 1) {
                item.params.lastFrame = item.params.firstFrame;
            }
            setFormData('video', item.params);
        }
    }, []);

    // 处理视频播放状态变化
    const handleVideoPlay = useCallback(
        (videoId, num, isPlaying) => {
            if (isPlaying) {
                // 开始播放，设置全局状态
                setVideoId(videoId);
                setvideoSelectNum(num);
            } else {
                // 停止播放，清除全局状态
                setVideoId('');
                setvideoSelectNum('');
            }
        },
        [setVideoId, setvideoSelectNum]
    );

    // 处理点击非视频区域时的暂停逻辑
    const handlePauseOnClick = () => {
        setVideoId('');
        setvideoSelectNum('');
    };
    // 创建一个工具函数来过滤掉parameters字段
    const getDisplayParams = (params) => {
        if (!params) return {};

        // 创建一个新的对象，排除parameters字段
        const { parameters, ...displayParams } = params;
        return displayParams;
    };

    const regenerateVideo = async () => {
        //需要滚动到顶部
        //跳转到顶部
        if (document.querySelector('.video-library-list')) {
            document
                .querySelector('.video-library-list')
                .scrollTo({ top: 0, behavior: 'auto' });
        }
        if (item.type === 'image') {
            const newparams = {
                version: '7',
                prompts: '',
                ratio: '9:16',
                bRefs: [],
                sRefs: [],
                uRefs: [],
                modelStyle: 0,
                isRaw: 0, //草图模式
                stylize: 0.5,
                particularity: 0.5,
                diversity: 0.5,
                speed: 1,
                resolution: 'high',
                ...getDisplayParams(item.params),
            };
            // console.log(newparams, 'item');

            //生图请求
            try {
                const response = await api.post('/v1/tob/diffusion', newparams);
                if (response.status === 200) {
                    //成功生成中就先触发一次重新加载
                    addfake(
                        {
                            jobId: response.data.jobId,
                            params: item.params,
                            type: item.type,
                            status: response.data.status,
                            resultUrl: [],
                        },
                        'image'
                    );
                }
            } catch (error) {}
        } else if (item.type === 'video') {
            try {
                const response = await api.post(
                    '/v1/tob/video-diffusion',
                    item.params
                );
                if (response.status === 200) {
                    //成功生成中就先触发一次重新加载
                    addfake(
                        {
                            jobId: response.data.jobId,
                            params: item.params,
                            type: item.type,
                            status: response.data.status,
                            resultUrl: [],
                        },
                        'video'
                    );
                }
            } catch (error) {}
        }
    };

    return (
        <div className={`video-library-list-item `}>
            <div className="video-library-videocontainer">
                {item.jobId &&
                    (item.resultUrl?.length > 0
                        ? item.resultUrl
                        : [...Array(item.params.onceGenerateNum || 4).keys()]
                    ).map((sitem, index) => {
                        const isThisVideoPlaying =
                            videoId === item.jobId && videoSelectNum === index;
                        return (
                            <div
                                className={`video-library-videocontainer-video ${
                                    horizontalRatios.includes(
                                        item.params?.ratio || '1:1'
                                    )
                                        ? `video-library-videocontainer-video-horizontal`
                                        : `video-library-videocontainer-video-vertical`
                                } ${item.params?.ratio || '1:1'}`}
                                key={index}
                                style={{
                                    aspectRatio:
                                        item.params?.ratio?.replace(':', '/') ||
                                        1 / 1,
                                }}
                            >
                                {item.status == (1 || 0) && (
                                    <>
                                        <GradientBackground
                                            key={`gradient-${item.jobId}-${index}`}
                                        ></GradientBackground>

                                        <div className="pedding-tag">
                                            生成中
                                        </div>
                                    </>
                                )}

                                {item.status == 3 && (
                                    <>
                                        <GradientBackground
                                            key={`gradient-${item.jobId}-${index}`}
                                        ></GradientBackground>

                                        <div className="pedding-tag fail-tag">
                                            生成失败
                                        </div>

                                        <div
                                            className="re-generate-btn"
                                            onClick={() => {
                                                regenerateVideo();
                                            }}
                                        >
                                            重试
                                        </div>
                                    </>
                                )}
                                {item.status == 2 && item.type === 'image' && (
                                    <div
                                        className="relative-container"
                                        onClick={() => {
                                            handlepop(item, index);
                                        }}
                                    >
                                        <LazyImage
                                            ratio={
                                                horizontalRatios.includes(
                                                    item.params?.ratio || '1:1'
                                                )
                                                    ? `horizontal`
                                                    : `vertical`
                                            }
                                            src={item.resultUrl[index] || ''}
                                            alt=""
                                        />
                                    </div>
                                )}

                                {item.status == 2 && item.type === 'video' && (
                                    <CustomControlVideoPlayer
                                        id={item.jobId}
                                        num={index}
                                        src={item.resultUrl[index]}
                                        poster={item.firstFrame}
                                        onVideoClick={() =>
                                            handlepop(item, index)
                                        }
                                        onPlay={handleVideoPlay}
                                        isPlaying={isThisVideoPlaying}
                                        onPauseOnClick={handlePauseOnClick}
                                    />
                                )}

                                <ButtonToolList
                                    data={item}
                                    imageUrl={item.resultUrl[index]}
                                    index={index}
                                    loadVideo={loadVideo}
                                ></ButtonToolList>
                            </div>
                        );
                    })}
            </div>
            <div className="video-detail">
                <div>
                    <div className="video-detail-type">
                        {item.type === 'image' && (
                            <div className="before-icon">
                                {!item.params?.bRefs?.length &&
                                !item.params?.sRefs?.length &&
                                !item.params?.uRefs?.length ? (
                                    <div className="before-icon-text">
                                        <img
                                            src="https://img.alicdn.com/imgextra/i1/O1CN01z88u6k1GH16rIXJce_!!6000000000596-2-tps-10-10.png"
                                            alt=""
                                        />
                                    </div>
                                ) : (
                                    <>
                                        {(() => {
                                            const allImages = [
                                                ...(item.params?.bRefs ?? []),
                                                ...(item.params?.sRefs ?? []),
                                                ...(item.params?.uRefs ?? []),
                                            ];
                                            const maxDisplay = 6; // 最多显示 6 张
                                            const displayImages =
                                                allImages.slice(0, maxDisplay);
                                            const remainingCount =
                                                allImages.length - maxDisplay;

                                            return (
                                                <>
                                                    {displayImages.map(
                                                        (img, index) => (
                                                            <img
                                                                className="before-icon-img"
                                                                key={index}
                                                                src={img}
                                                                alt=""
                                                            />
                                                        )
                                                    )}
                                                    {remainingCount > 0 && (
                                                        <span className="remaining-count">
                                                            {remainingCount}+
                                                        </span>
                                                    )}
                                                </>
                                            );
                                        })()}
                                    </>
                                )}
                            </div>
                        )}

                        {item.type === 'video' && (
                            <div className="before-icon image2video-icon">
                                <div className="img-cover">
                                    <img src={item.params.firstFrame} alt="" />
                                </div>
                            </div>
                        )}

                        {item.type === 'image' && item.jobType == 1
                            ? item.params.type == 'reroll'
                                ? '再次生图'
                                : kuozhan[item.params.type][
                                      item.params.type == 'remix'
                                          ? item.params.parameters.mode
                                          : item.params.parameters.type
                                  ]
                            : types[item.type]}
                    </div>
                    <p className="video-prompt">{item.params.prompts}</p>

                    {item.type === 'image' ? (
                        <div className="tag-list">
                            <p>比例{item.params.ratio}</p>
                            <p>模型{item.params.version}</p>
                        </div>
                    ) : (
                        <div className="tag-list">
                            <p>5s</p>
                            {/* <p>比例{item.params.ratio}</p> */}
                            <p>模型{item.params.version}</p>
                            <p>
                                {item.params.motionSpeed == 'low'
                                    ? '慢速运动'
                                    : '快速运动'}
                            </p>
                        </div>
                    )}
                </div>
                {(item.status == 2 || item.status == 3) && (
                    <div className="video-tool">
                        <button
                            onClick={() => {
                                handleRewrite(item);
                            }}
                        >
                            <img
                                src="https://img.alicdn.com/imgextra/i1/O1CN018C66oO29w3UxExzzO_!!6000000008131-55-tps-16-16.svg"
                                alt=""
                            />
                        </button>
                        <div className="video-tool-generate">
                            <button
                                className="video-tool-generate-button"
                                onClick={() => {
                                    regenerateVideo();
                                }}
                            >
                                <img
                                    src="https://img.alicdn.com/imgextra/i2/O1CN01Y3gSLx1IuWXRpDLpK_!!6000000000953-55-tps-16-16.svg"
                                    alt=""
                                />
                            </button>
                        </div>

                        <DeleteButton
                            data={{ jobId: item.jobId, no: -1 }}
                            handleDeleteComplete={loadVideo}
                        ></DeleteButton>
                    </div>
                )}
            </div>
        </div>
    );
});
export default VideoItem;
